package com.Gientech.redisdemo.Controller;


import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
public class ConsumerController {

//    @Autowired
//    private RestTemplate restTemplate;
//
//    @Autowired
////    private DiscoveryClient discoveryClient;
//
//    @GetMapping("/consumer-test")
//    public String test() throws Exception{

//        List<ServiceInstance> instances = this.discoveryClient.getInstances("provider");
//        ServiceInstance serviceInstance = instances.get(0);
//        URI uri = serviceInstance.getUri();

//        String targetUrl = uri + "/test";
//        String rst = this.restTemplate.getForObject(targetUrl, String.class);

//        return "consumer-test:" + rst;
//    }

    @GetMapping("/consumer")
    public void consumer() throws Exception{
        DefaultMQPushConsumer consumer= new DefaultMQPushConsumer("consumer");
        consumer.setNamesrvAddr("127.0.0.1:9876");
        //订阅消费者
        consumer.subscribe("TopicTest","*");
        //注册回调实现类，来处理从broker拉取回来的消息
        //消费模式
        consumer.setMessageModel(MessageModel.BROADCASTING);
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                System.out.printf("%s receive new message: %s %n",Thread.currentThread().getName(),msgs);
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        //启动消费者实例
        consumer.start();
        System.out.println("consumer start");

    }
}
